import {Injectable} from '@angular/core';
import {MessageBody} from '../model/message-body';
import {webSocket, WebSocketSubject} from 'rxjs/webSocket';
import {environment} from '../../environments/environment';

@Injectable()
export class MessageSocketService {
  private readonly socketUrl = environment.webSocketUrl;
  subject$: WebSocketSubject<MessageBody>;
  private id;

  constructor() {
  }

  open(id): WebSocketSubject<MessageBody> {
    this.id = id.toString();
    this.subject$ = this.createWebSocket();
    return this.subject$;
  }

  send(message) {
    this.subject$.next(message);
  }

  createWebSocket() {
    return webSocket<MessageBody>({
      url: this.socketUrl + this.id
    });
  }

  close() {
    this.subject$.complete();
  }
}
